package com.jz.community.moduleshopping.address.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.UserInfo;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.GetUserInfoTask;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.view.DividerItemDecoration;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.address.adapter.NearShopListAdapter;
import com.jz.community.moduleshopping.address.adapter.UserOrderAddressListAdapter;
import com.jz.community.moduleshopping.address.bean.BaseAddressInfo;
import com.jz.community.moduleshopping.address.bean.UserAddressInfo;
import com.jz.community.moduleshopping.address.task.DeleteAddressTask;
import com.jz.community.moduleshopping.address.task.GetAddressListTask;
import com.jz.community.moduleshopping.confirmOrder.bean.ShopSelfAddressInfo;
import com.jz.community.moduleshopping.confirmOrder.task.GetShopSelfAddressTask;
import com.jz.community.moduleshopping.utils.SpUtils;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/5/3 09:37
 * <p>
 * 收货地址列表
 */
@Route(path = RouterIntentConstant.MODULE_SHOPPING_ADDRESS_LIST)
public class ReceivingAddressListActivity extends BaseMvpActivity {
    @BindView(R2.id.coupon_list_back)
    ImageView couponListBack;
    @BindView(R2.id.coupon_list_title)
    TextView couponListTitle;
    @BindView(R2.id.coupon_list_find)
    ImageView couponListFind;
    @BindView(R2.id.custom_tool_bar_menu)
    Toolbar customToolBarMenu;
    @BindView(R2.id.view_line_four)
    TextView viewLineFour;
    @BindView(R2.id.tv_goods_receipt_name)
    TextView tvGoodsReceiptName;
    @BindView(R2.id.tv_goods_receipt_phone)
    TextView tvGoodsReceiptPhone;
    @BindView(R2.id.ll_edit_name_and_phone)
    LinearLayout llEditNameAndPhone;
    @BindView(R2.id.tv_address_line)
    TextView tvAddressLine;
    @BindView(R2.id.near_pickup_address_line)
    View nearPickupAddressLine;
    @BindView(R2.id.iv_arrow_right)
    ImageView ivArrowRight;
    @BindView(R2.id.ll_to_choose_server_point)
    LinearLayout llToChooseServerPoint;
    @BindView(R2.id.rv_nearest_server_point)
    RecyclerView rvNearestServerPoint;
    @BindView(R2.id.ll_server_point_user_massage)
    LinearLayout llServerPointUserMassage;
    @BindView(R2.id.tv_usefor_address)
    TextView tvUseforAddress;
    @BindView(R2.id.tv_user_manager_line)
    TextView tvUserManagerLine;
    @BindView(R2.id.rv_my_address_list)
    RecyclerView rvMyAddressList;
    @BindView(R2.id.ll_myself_address)
    LinearLayout llMyselfAddress;
    private ShopSelfAddressInfo.EmbeddedBean selfAddressInfo;
    private NearShopListAdapter nearShopListAdapter;
    private static final int REQUEST_SELF_CODE = 0X00002;
    private static final int REQUEST_UPDATE_USER_CODE = 0X00004;
    public static final int REQUEST_ADD_USER_CODE = 0X00005;
    private UserOrderAddressListAdapter userOrderAddressListAdapter;
    private LoadService loadService;
    private int sendType;
    private int addressFrom;
    private List<BaseAddressInfo> userAddressInfoList;
    private String shopId;
    private String lat;
    private String lon;
    private String selfType;
    private int goodFrom;
    private int source;
    private boolean isDistributable = true;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_add_list;
    }

    @Override
    protected void initView() {
        handleTitleShow();
        setImmersionBar(customToolBarMenu);
    }

    private void handleTitleShow() {
        if (!Preconditions.isNullOrEmpty(SpUtils.getInstance().getConsigneeName(this))) {
            tvGoodsReceiptName.setText(SpUtils.getInstance().getConsigneeName(this));
            tvGoodsReceiptPhone.setText(SpUtils.getInstance().getConsigneePhone(this));
        } else {
            getPwdUserInfoMsg();
        }
    }

    @Override
    protected void initDatas() {
        selfAddressInfo = (ShopSelfAddressInfo.EmbeddedBean) getIntent().getSerializableExtra("selfAddress");
        sendType = getIntent().getIntExtra("sendType", 0);
        addressFrom = getIntent().getIntExtra("addressFrom", 1);
        goodFrom = getIntent().getIntExtra("goodFrom", -1);
        source = getIntent().getIntExtra("source", -1);
        shopId = getIntent().getStringExtra("shopId");
        lat = getIntent().getStringExtra("lat");
        lon = getIntent().getStringExtra("lon");
        selfType = getIntent().getStringExtra("selfType");
        showFromTitle();
        handleAddressFromStatus(addressFrom);
        handleSourceGoodsType();
        getUserAddress();
    }

    /**
     * 用户信息
     */
    private void getPwdUserInfoMsg() {
        new GetUserInfoTask(this, o -> {
            UserInfo userInfo = (UserInfo) o;
            if (!Preconditions.isNullOrEmpty(userInfo)) {
                tvGoodsReceiptName.setText(SpUtils.getInstance().getConsigneeName(this));
                tvGoodsReceiptPhone.setText(SpUtils.getInstance().getConsigneePhone(this));
            }
        }).execute();
    }

    /**
     * 365 商品类型处理
     */
    private void handleSourceGoodsType() {
        if (source == 3) {
            SHelper.gone(llServerPointUserMassage);
        } else {
            handleBindNearShopAdapter();
        }
    }

    /**
     * 是否配送、自提状态
     *
     * @return
     */
    private boolean isDistributable() {
        if (!Preconditions.isNullOrEmpty(selfAddressInfo) && Preconditions.isNullOrEmpty(selfAddressInfo.getContent())) {
            return selfAddressInfo.getContent().get(0).isDistributable();
        }
        return true;
    }

    /**
     * 显示不同来标题
     */
    private void showFromTitle() {
        couponListTitle.setText("地址");
    }

    /**
     * 不同来源状态UI展示
     *
     * @param addressFrom
     */
    private void handleAddressFromStatus(int addressFrom) {
        if (addressFrom == 0) {
            SHelper.gone(llServerPointUserMassage);
        } else {
            SHelper.vis(llServerPointUserMassage);
        }
    }

    private void getUserAddress() {
        new GetAddressListTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                UserAddressInfo userAddressInfo = (UserAddressInfo) o;
                if (!Preconditions.isNullOrEmpty(userAddressInfo)) {
                    UserAddressInfo.EmbeddedBean embeddedBean = userAddressInfo.get_embedded();
                    handleBindUserAddressAdapter(embeddedBean);
                }
            }
        }).execute();
    }
    @Override
    protected void addListener() {

        loadService = LoadSir.getDefault().register(rvMyAddressList, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                if (loadService.getCurrentCallback() == ErrorCallback.class) {
                    getUserAddress();
                }
            }
        });

        loadService.setCallBack(EmptyCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                ImageView mIvEmpty = view.findViewById(R.id.empty_img);
                TextView mTvEmpty = view.findViewById(R.id.empty_tv);
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mIvEmpty.getLayoutParams();
                params.topMargin = SHelper.dp2px(ReceivingAddressListActivity.this, 80);
                mIvEmpty.setLayoutParams(params);
                mIvEmpty.setImageResource(R.mipmap.ic_address_empty);
                mTvEmpty.setText("寄到哪儿?");
            }
        });

        llToChooseServerPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReceivingAddressListActivity.this, SelfAddressListActivity.class);
                intent.putExtra("selfAddress", selfAddressInfo);
                intent.putExtra("shopId", shopId);
                intent.putExtra("lat", lat);
                intent.putExtra("lon", lon);
                intent.putExtra("selfType", selfType);
                startActivityForResult(intent, REQUEST_SELF_CODE);
            }
        });

        llEditNameAndPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReceivingAddressListActivity.this, UpdateUserMsgActivity.class);
                startActivityForResult(intent, REQUEST_UPDATE_USER_CODE);
            }
        });

        couponListFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ReceivingAddressListActivity.this, AddAddressActivity.class);
                startActivityForResult(intent, REQUEST_ADD_USER_CODE);
            }
        });

        couponListBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 附近自提列表
     */
    private void handleBindNearShopAdapter() {
        if (!Preconditions.isNullOrEmpty(selfAddressInfo) && !Preconditions.isNullOrEmpty(selfAddressInfo.getContent())) {
            LinearLayoutManager goods_layoutManager = new LinearLayoutManager(this);
            rvNearestServerPoint.setHasFixedSize(true);
            rvNearestServerPoint.setFocusable(false);
            rvNearestServerPoint.setLayoutManager(goods_layoutManager);
            rvNearestServerPoint.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            nearShopListAdapter = new NearShopListAdapter(R.layout.module_shopping_item_near_shop_list, selfAddressInfo.getContent(), "1");
            rvNearestServerPoint.setAdapter(nearShopListAdapter);
            nearShopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intent = new Intent();
                    intent.putExtra("isSelf", false);
                    intent.putExtra("address", nearShopListAdapter.getData().get(position).getAddress());
                    intent.putExtra("mentionName", nearShopListAdapter.getData().get(position).getName());
                    intent.putExtra("tel", nearShopListAdapter.getData().get(position).getContact_tel());
                    intent.putExtra("distance", nearShopListAdapter.getData().get(position).getDistance());
                    intent.putExtra("cityCode", nearShopListAdapter.getData().get(position).getCityCode());
                    intent.putExtra("mentionId", ConverterUtils.toString(nearShopListAdapter.getData().get(position).getId()));
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
        }else {
            SHelper.gone(llToChooseServerPoint,nearPickupAddressLine);
        }
    }

    /**
     * 用户收货地址列表
     */
    private void handleBindUserAddressAdapter(UserAddressInfo.EmbeddedBean embeddedBean) {
        if (!Preconditions.isNullOrEmpty(embeddedBean) && !Preconditions.isNullOrEmpty(embeddedBean.getContent())) {
            SHelper.vis(llMyselfAddress);
            loadService.showSuccess();
            LinearLayoutManager goods_layoutManager = new LinearLayoutManager(this);
            rvMyAddressList.setLayoutManager(goods_layoutManager);
            rvMyAddressList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            Collections.reverse(embeddedBean.getContent());
            userOrderAddressListAdapter = new UserOrderAddressListAdapter(getUserAddressInfo(embeddedBean.getContent()), sendType, isDistributable());
            rvMyAddressList.setAdapter(userOrderAddressListAdapter);
            userOrderAddressListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    orderFromAddressResult(position);
                }
            });

            userOrderAddressListAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                    deleteAddressDialog(userOrderAddressListAdapter.getData().get(position).getId() + "", position);
                    return false;
                }
            });

            userOrderAddressListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId() == R.id.iv_edit_address) {
                        Bundle bundle = new Bundle();
                        Intent intent = new Intent(ReceivingAddressListActivity.this, AddAddressActivity.class);
                        bundle.putString("name", userOrderAddressListAdapter.getData().get(position).getName());
                        bundle.putString("phone", userOrderAddressListAdapter.getData().get(position).getPhone());
                        bundle.putString("address", userOrderAddressListAdapter.getData().get(position).getAddress());
                        bundle.putString("addressDetails", userOrderAddressListAdapter.getData().get(position).getAddressDetails());
                        bundle.putString("id", userOrderAddressListAdapter.getData().get(position).getId());
                        intent.putExtras(bundle);
                        startActivityForResult(intent, ReceivingAddressListActivity.REQUEST_ADD_USER_CODE);
                    }
                }
            });
        } else {
            SHelper.gone(llMyselfAddress);
            loadService.showCallback(EmptyCallback.class);
        }
    }

    /**
     * 不同地址来源跳转回调处理
     *
     * @param position
     */
    private void orderFromAddressResult(int position) {

        if (addressFrom == 0) {
            return;
        }

        if (isPickSendAddress()) {
            checkIsDistributable(userOrderAddressListAdapter.getData().get(position).getLatitude(), userOrderAddressListAdapter.getData().get(position).getLongitude(), "4");
            if (!isDistributable) {
                WpToast.l(this, "不在配送范围！");
            } else {
                Intent intent = new Intent();
                intent.putExtra("isSelf", true);
                intent.putExtra("address", userOrderAddressListAdapter.getData().get(position).getAddress() + userOrderAddressListAdapter.getData().get(position).getAddressDetails());
                intent.putExtra("mentionName", userOrderAddressListAdapter.getData().get(position).getName());
                intent.putExtra("tel", userOrderAddressListAdapter.getData().get(position).getPhone());
                intent.putExtra("cityCode", userOrderAddressListAdapter.getData().get(position).getCityCode());
                intent.putExtra("addressId", userOrderAddressListAdapter.getData().get(position).getServiceData());
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    }

    /**
     * 检查是否在配送范围
     *
     * @param lat
     * @param lon
     */
    private void checkIsDistributable(String lat, String lon, String type) {
        if (goodFrom == 0) {
            new GetShopSelfAddressTask(this, o -> {
                ShopSelfAddressInfo shopSelfAddressInfo = (ShopSelfAddressInfo) o;
                if (!Preconditions.isNullOrEmpty(shopSelfAddressInfo) && !Preconditions.isNullOrEmpty(shopSelfAddressInfo.get_embedded())) {
                    isDistributable = shopSelfAddressInfo.get_embedded().getContent().get(0).isDistributable();
                }
            }).execute(shopId, lon, lat, type,"");
        }

    }

    /**
     * 是否支持自提配送地址
     *
     * @return
     */
    private boolean isPickSendAddress() {
        if (sendType == 2 || !isDistributable()) {
            WpToast.l(this, "仅支持自提点！");
            return false;
        }
        return true;
    }

    /**
     * status (integer, optional): 状态(0正常 -1删除,默认正常:0)
     *
     * @param contentBeans
     * @return
     */
    private List<BaseAddressInfo> getUserAddressInfo(List<BaseAddressInfo> contentBeans) {
        userAddressInfoList = new ArrayList<>();
        for (BaseAddressInfo contentInfo : contentBeans) {
            filterUserAddressList(contentInfo);
        }
        return userAddressInfoList;
    }

    /**
     * 过滤用户地址
     *
     * @param contentInfo
     */
    private void filterUserAddressList(BaseAddressInfo contentInfo) {
        if (contentInfo.getStatus() == 0) {
            BaseAddressInfo contentBean = new BaseAddressInfo();
            contentBean.setId(contentInfo.getId());
            contentBean.setAddress(contentInfo.getAddress());
            contentBean.setAddressDetails(contentInfo.getAddressDetails());
            contentBean.setIsDefault(contentInfo.getIsDefault());
            contentBean.setName(contentInfo.getName());
            contentBean.setPhone(contentInfo.getPhone());
            contentBean.setServiceData(contentInfo.getServiceData());
            contentBean.setLatitude(contentInfo.getLatitude());
            contentBean.setLongitude(contentInfo.getLongitude());
            contentBean.setCityCode(contentInfo.getCityCode());
            userAddressInfoList.add(contentBean);
        }
    }

    /**
     * 删除地址弹框
     *
     * @param id
     */
    private void deleteAddressDialog(String id, int position) {
      AlertDialog alertDialog=  new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("你确定删除该收货地址吗？")
                .setNegativeButton("取消", null)
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!Preconditions.isNullOrEmpty(id)) {
                            deleteAddressTask(id, position);
                        }
                    }
                }).show();
        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
        alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
    }

    /**
     * 删除地址请求
     *
     * @param id
     */
    private void deleteAddressTask(String id, int position) {
        new DeleteAddressTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                boolean b = (boolean) o;
                if (b) {
                    WpToast.l(ReceivingAddressListActivity.this, "删除成功");
                    userOrderAddressListAdapter.getData().remove(position);
                    userOrderAddressListAdapter.notifyDataSetChanged();
                    if (Preconditions.isNullOrEmpty(userOrderAddressListAdapter.getData())) {
                        loadService.showCallback(EmptyCallback.class);
                        SHelper.gone(llMyselfAddress);
                    }
                } else {
                    WpToast.l(ReceivingAddressListActivity.this, "删除失败");
                }
            }
        }).execute(id);
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELF_CODE && resultCode == RESULT_OK) {
            setResult(RESULT_OK, data);
            finish();
        } else if (requestCode == REQUEST_UPDATE_USER_CODE && resultCode == RESULT_OK) {
            handleTitleShow();
        } else if (requestCode == REQUEST_ADD_USER_CODE && resultCode == RESULT_OK) {
            getUserAddress();
            handleTitleShow();
        }
    }
}
